﻿// which API are we going to use?
var SMUGMUG_CONNECTION_STRING = "http://api.smugmug.com/services/api/json/1.2.1/";
// what is the URL for the random images?
var SMUGMUG_RANDOM_IMAGE_STRING = "http://www.smugmug.com/photos/random.mg?AlbumID={ALBUM_ID}&Size=S";
// what API key to use?
var SMUGMUG_API_KEY = "9ndFKFokRmEdEdjU5TGAJOolpo7NQ4IV";

var SMUGMUG_POST = "POST";
var SMUGMUG_GET = "GET";

var SMUGMUG_USER_AGENT = "SmugMugSlideshow-v.0.0.1";

// how long should a fade last?
var SMUGMUG_FADE_DURATION = 3000;

// how much to reduce the image for margins
var SMUGMUG_MARGIN_PIXELS = 2;

// how often to refres the image. TO DO - move this to an option.
var SMUGMUG_REFRESH_INTERVAL = 30000;

// sessions expire after 6 hours (5.5 hours in milliseconds is our expiration).
var SMUGMUG_SESSION_EXPIRATION = 19800000;

// what API methods are we going to use?
var SMUGMUG_LOGIN_ANONYMOUSLY = "smugmug.login.anonymously";
var SMUGMUG_ALBUMS_GET = "smugmug.albums.get";
var SMUGMUG_IMAGES_GET = "smugmug.images.get";
var SMUGMUG_IMAGES_GETFINO = "smugmug.images.getInfo";

// status messages
// invalid user
var SMUGMUG_STATUS_CODE_4 = "Couldn't find any albums. Check the nickname in options.";
var SMUGMUG_STATUS_CODE_18 = "Invalid API key.";
var SMUGMUG_STATUS_SUCCESS = "success";

// internal status codes
//var SMUGMUG_INTERNAL_STATUS_CODE_10001 = 10001;
//var SMUGMUG_STATUS_CODE_10001 = "Couldn't find any albums";

// constructor
function SmugMug(){
  this._connString = SMUGMUG_CONNECTION_STRING;
  this._apiKey = SMUGMUG_API_KEY;
	this._sessionId = null;
  this._sessionExpire = null;
  this._method = null;
  this._albums = [];
	this._albumsLastFetch = [];
  this._url = null;
  this._request = null;
	this._currentImg1 = true;
	this._currentImgMeta = null;

	gadget.debug.trace("SmugMugSlideshow: Starting");

}

SmugMug.prototype._apiKey;
SmugMug.prototype._sessionID;
SmugMug.prototype._method;
SmugMug.prototype._ConnString;

SmugMug.prototype._checkStatus = function(code) {
	switch(code)
	{
	case 4:
		return SMUGMUG_STATUS_CODE_4;
		break;
	case 18:
		return SMUGMUG_STATUS_CODE_18;
		break;
	default:
		return code;
	}
}

SmugMug.prototype.randomImageGet = function() {
	// TO DO - figure out date handling:if ((!this._albums.length) || (this._albumsLastFetch - testdate)) {
	try {
		lblMessages.visible = false;
		if ((!this._albums.length)) {
			gadget.debug.trace("SmugMugSlideshow: Didn't find albums, getting albums.")
			// TO DO - get nickname, fail if not in the prefs.
			var nickname = options.getValue("NickName")
			if (nickname == "") {
				//img1.visible = false;
				//img2.visible = false;
				lblMessages.visible = true;
				lblMessages.innerText = "You must enter a value for nickname in the options.";
				gadget.debug.trace("SmugMugSlideshow: No nickname in options, waiting...")
				return false;
			} else {
				img1.visible = true;
				img2.visible = true;
				lblMessages.visible = false;
				// Try to get albums. If it fails, throw an error.
				var success = this.albumsGet(nickname);
				if (success != SMUGMUG_STATUS_SUCCESS) {
					throw(success);
				};
			}
		}
		
		var albumsMax = this._albums.length;
		var randomAlbum = Math.round(albumsMax * Math.random())
		//this.randomImageGetViaUrl(randomAlbum);
		this._randomImageGetUrlViaApi(randomAlbum);
		
	} catch (e) {
			lblMessages.visible = true;
			lblMessages.innerText = this._checkStatus(success);
	}

	// TO DO - call the method that fetches and image and updates the image in the gadget
	// TO DO - update the label with the gallery name
	// TO DO - update the label with the image name
};

SmugMug.prototype.imageDblClick = function() {
	framework.openUrl("http://www.google.com");
}

SmugMug.prototype._sessionExpiredCheck = function() {
	// returns true if the session is null or expired.

	var now = new Date();

	if ((this._session == null) || (now.getTime() > this._sessionExpire)) {
		gadget.debug.trace("SmugMugSlideshow: Found current session.");
		return true;
	} else {
		gadget.debug.trace("SmugMugSlideshow: Didn't find current session.");
		return 	false;
	}
};

SmugMug.prototype._fadeImages = function(src) {
	var outImage;
	var inImage;

	if (this._currentImg1) {
		outImage = img2;
		inImage = img1;
		img1.src = this._request.responseStream;	
		img1.width = this._makeSize()-SMUGMUG_MARGIN_PIXELS;
		img1.x = (view.width - img1.width) / 2
		img1.height = this._makeSize()-SMUGMUG_MARGIN_PIXELS;
	} else {
		outImage = img1;
		inImage = img2;
		img2.src = this._request.responseStream;
		img2.width = this._makeSize()-SMUGMUG_MARGIN_PIXELS;
		img2.x = (view.width - img2.width) / 2
		img2.height = this._makeSize()-SMUGMUG_MARGIN_PIXELS;
	}

	view.beginAnimation(function() { setElementOpacity(outImage); }, // callback
		255, // start value, 255 = full opacity
		0, // end value, 0 = no opacity or "hidden"
		SMUGMUG_FADE_DURATION); // duration in milliseconds

	view.beginAnimation(function() { setElementOpacity(inImage); }, // callback
		0, // start value 0 = no opacity or "hidden"
		255, // end value, 255 = full opacity
		SMUGMUG_FADE_DURATION); // duration in milliseconds  

	this._currentImg1 = !this._currentImg1;
}

SmugMug.prototype._randomImageGetUrlViaApi = function(albumIndex) {
	gadget.debug.trace("SmugMugSlideshow: Getting random image from " + this._albums[albumIndex][1] + ".");
	this._method = SMUGMUG_IMAGES_GET
	var parms = "AlbumID=" + this._albums[albumIndex][0];
	this._url = this._makeUrl(false, parms);
	this._makeRequest(false);
	var myObj = eval( '(' + this._request.responseText + ')' );
	var maxlen = myObj.Images.length;
	var randomImageIndex = Math.round(maxlen * Math.random())

	this._method = SMUGMUG_IMAGES_GETFINO;
	parms = "ImageID=" + myObj.Images[randomImageIndex].id;
	
	this._url = this._makeUrl(false, parms);
	this._makeRequest(false);
	
	var myObj = eval( '(' + this._request.responseText + ')' );
	//this._fadeImages(myObj.Image[0].SmallURL)
  this._randomImgMeta = myObj;
	this.randomImageGetViaUrl(myObj.Image.SmallURL);

}

SmugMug.prototype.randomImageGetViaUrl = function(url) {
	this._url = url;
	//var viewMin = (this._makeSize() - SMUGMUG_MARGIN_PIXELS) + "x" + (this._makeSize() - SMUGMUG_MARGIN_PIXELS );
  //this._url = this._url.replace("{SIZE}", viewMin);
	
	this._makeRequest(false);
	
	this._fadeImages();
}

SmugMug.prototype._makeSize = function() {
	var minsize;
	minsize = Math.min(view.width, view.height);

	return minsize;
}

SmugMug.prototype.albumsGet = function(nickname) {
	if (this._sessionExpiredCheck()) {
		gadget.debug.trace("SmugMugSlideshow: Session expired, need to login.");
		this._login();
	}
	
	this._method = SMUGMUG_ALBUMS_GET;
	var parms = "NickName=" + nickname;
	this._url = this._makeUrl(false, parms);

	var albumrequest = this._makeRequest(false);
  
  var myObj = eval( '(' + this._request.responseText + ')' );
	if (myObj.stat == "ok") {
		// we got a valid response. Check to see if we got any albums.
		if (!myObj.Albums.length) {
			return SMUGMUG_STATUS_CODE_4;
		}
		gadget.debug.trace("SmugMugSlideshow: found " + myObj.Albums.length + " albums");
		var albuminfo = [];
		for (i=0;i<myObj.Albums.length;i++){
			albuminfo = [myObj.Albums[i].id, myObj.Albums[i].Title];
			this._albums.push(albuminfo);
		}
		return SMUGMUG_STATUS_SUCCESS;
	} else {
		return myObj.code;
	}
	
}

SmugMug.prototype._login = function() {
  this._method = SMUGMUG_LOGIN_ANONYMOUSLY;
	var parameters = [];
  this._url = this._makeUrl(true, parameters);

  var loginrequest = this._makeRequest(false);
  
  var myObj = eval( '(' + this._request.responseText + ')' );

	if (myObj.stat == "ok") {
		var now = new Date();
		this._sessionId = myObj.Login.Session.id;
		this._sessionExpire = now.getTime() + SMUGMUG_SESSION_EXPIRATION;
	}
};

SmugMug.prototype._makeUrl = function(useApiKey, parms) {
  var connString = this._connString;
	var apiMethod = "?method=" + this._method;
	var apiKey = useApiKey == false ? "" : "&APIKey=" + this._apiKey;

	var parametersOut = "";
	if (parms != null) {
		parametersOut = "&" + parms;
	};

	
  var sessionId = this._sessionId == null ? "" : "&SessionID=" + this._sessionId + parametersOut;
  
	var url = SMUGMUG_CONNECTION_STRING + apiMethod + apiKey + sessionId;
	
  return url;
};

SmugMug.prototype._makeRequest = function(async) {
	this._request = new XMLHttpRequest();
	try {
		this._request.open(SMUGMUG_GET, this._url, async);
	} catch (e) {
		
		this._request = null;
    return
	};

	this._request.onreadystatechange = createObjectCallback(this._request, this._onData);

	// Start the download	
  try {
		this._request.send();
  } catch (e) {
    return;
  }

	//return this._request;
	return;
};

SmugMug.prototype._onData = function() {
	try {
		if (this.readyState != 4) {
			return;
		}

		if (this.status != 200) {
			return;
		}
	} catch(e) {
		// TO DO - throw error up chain.
	}

	// if we got here we should have a readyState = 4
  //alert(this.responseText);

  return;
};

function createObjectCallback(obj, fn){
	return function() { fn.apply(obj, arguments); };
}

var smugMugInst;
var smugMug_Gadget = {};

smugMug_Gadget.onOpen = function() {
	img1.x = (view.width - img1.width) / 2;
	img2.x = (view.width - img2.width) / 2;

	smugMugInst = new SmugMug();
	smugMugInst._currentImg1 = true;

	smugMugInst.randomImageGet();
	view.setInterval(createObjectCallback(smugMugInst, smugMugInst.randomImageGet), SMUGMUG_REFRESH_INTERVAL);
}

smugMug_Gadget.onOptionChanged = function() {
	smugMugInst.randomImageGet();
};

function setElementOpacity(element) {
  element.opacity = event.value;
}
